package com.tuo51.foudation.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImgUtil {


    public static String getBase64(String url){
        InputStream in = saveToFile(url);
        return GetImageStrByInPut(in);
    }

    public static InputStream saveToFile(String destUrl){

        URL url = null;
        InputStream in = null;
        try{
            url = new URL(destUrl);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            in = httpUrl.getInputStream();
            return in;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取输入流,转换为Base64字符串
     * @param input
     * @return
     */
    public static String GetImageStrByInPut(InputStream input) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            data = new byte[input.available()];
            input.read(data);
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        Base64 encoder = new Base64();

//        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data).toString();// 返回Base64编码过的字节数组字符串
    }

    public static String getBase64(BufferedImage image){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "png", baos);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

        String data = DatatypeConverter.printBase64Binary(baos.toByteArray());

        return data;
    }

    public static Image loadImageFromClassPath(String path){
        Image anno_image = null;
        try {
            ClassPathResource resource = new ClassPathResource(path);
            InputStream inputStream = resource.getInputStream();
            anno_image = ImageIO.read(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return anno_image;
    }
}
